import { uuid } from '@/utils'
import {
  queryTpls,
  saveOrUpdateMeasurePointTemplate,
} from '@/api/modules/indicator'

export interface AssociationIndicator {

  pointCode: string

  energyCode: string
  measuringPointNumber: string
  indicatorName: string

  indicatorCode?: string
  /** 计量器具编码 */
  code: string
  /**
   * 计量器具关联指标编码=用能单元编码.MI.计量器具编码.测点编码
   * indicatorNumber = [pointCode].MI.[code].[measuringPointNumber]
   * @example
   * EU001.MI.CCL_030201.EA
   */
  indicatorNumber?: string
  indicatorMultiple?: number
  unitId: number | null
  unit?: string
  /** 标识模板数据 */
  _is_tpl_: boolean
  _uuid_: string

  id?: number
  toolsId?: number
}

export function generateIndicatorNumber(
  pointCode: string,
  code: string,
  measuringPointNumber: string,
  MI: string = 'MI',
) {
  return `${pointCode}.${MI}.${code}.${measuringPointNumber}`
}

function transferTpls(tpls: any[], pointCode: string, code: string): AssociationIndicator[] {
  return tpls.map((item) => {
    return {
      ...item,
      indicatorCode: '',
      pointCode,
      code,
      indicatorNumber: generateIndicatorNumber(pointCode, code, item.measuringPointNumber),
      indicatorMultiple: 1,
      _uuid_: uuid(),
      _is_tpl_: true,
      id: undefined,
    }
  })
}

/**
 * 计量器具关联测点
 */
export default function useMeasurePointTemplate() {
  const [tpls, setTpls] = useState<AssociationIndicator[]>([])
  const [loading, setLoading] = useState(false)

  const isInvalid = (val: any) => val === '' || val == null

  async function getTplsByEnergyCode(energyCode: string, pointCode: string, code: string) {
    setLoading(true)
    try {
      const { data } = await queryTpls(energyCode)
      setTpls(transferTpls(data, pointCode, code))
      setLoading(false)
    }
    catch (e) {
      console.warn(e)
      setTpls([])
      setLoading(false)
    }
  }

  async function removeIndicator(_uuid_: string) {
    setTpls(
      tpls.value.filter(
        item => item._uuid_ !== _uuid_,
      ),
    )

    // 由于VUE在patch时考虑到的性能优化处理
    // 在删除一行的数据后，它相关的dom节点有可能会被复用
    // 导致节点上面的校验错误样式会保留或消失
    // 所以，在删除后重新校验一次
    await nextTick()
    validate()
  }

  async function createEmptyTpl(energyCode: string, pointCode: string, code: string) {
    const isOk = validate()
    if (isOk) {
      tpls.value = [
        {
          id: undefined,
          pointCode,
          energyCode,
          code,
          measuringPointNumber: '',
          indicatorName: '',
          indicatorCode: '',
          indicatorNumber: generateIndicatorNumber(pointCode, code, ''),
          indicatorMultiple: 1,
          unitId: null,
          unit: '',
          _uuid_: uuid(),
          _is_tpl_: true,
        },
        ...tpls.value,
      ]
    }
  }

  async function saveTps(energyCode: string, cb?: () => void) {
    const isOk = validate()
    if (isOk) {
      await saveOrUpdateMeasurePointTemplate(
        energyCode,
        tpls.value.map(v => ({
          energyCode: v.energyCode,
          indicatorName: v.indicatorName,
          measuringPointNumber: v.measuringPointNumber,
          unit: v.unit,
          unitId: v.unitId,
        })),
      )
      ElMessage.success('保存成功')
      cb?.()
    }
    else {
      return Promise.reject(new Error('校验不通过'))
    }
  }

  function removeOneError(_uuid_: string, prop: string) {
    let elem = document.getElementById(`id_${_uuid_}_${prop}`)?.parentNode as HTMLElement
    if (prop === 'unitId' || prop === 'indicatorName')
      elem = document.getElementById(`id_${_uuid_}_${prop}`)?.querySelector('.el-input__wrapper') as HTMLElement

    elem?.style.setProperty('--el-input-border-color', 'var(--el-border-color)')
    elem?.style.setProperty('--el-input-hover-border-color', 'var(--el-border-color-hover)')
    elem?.style.setProperty('--el-input-focus-border-color', 'var(--el-color-primary)')
  }
  function addOneError(_uuid_: string, prop: string) {
    let elem = document.getElementById(`id_${_uuid_}_${prop}`)?.parentNode as HTMLElement
    if (prop === 'unitId' || prop === 'indicatorName')
      elem = document.getElementById(`id_${_uuid_}_${prop}`)?.querySelector('.el-input__wrapper') as HTMLElement

    elem?.style.setProperty('--el-input-border-color', 'var(--el-color-danger)')
    elem?.style.setProperty('--el-input-hover-border-color', 'var(--el-color-danger)')
    elem?.style.setProperty('--el-input-focus-border-color', 'var(--el-color-danger)')
  }
  function clearError() {
    try {
      const tableElem = document.getElementById('associationModalV2Table2')
      const inputWrappers = Array.from(tableElem?.querySelectorAll('.el-input__wrapper') ?? []) as HTMLElement[]
      for (const elem of inputWrappers) {
        elem?.style.setProperty('--el-input-border-color', 'var(--el-border-color)')
        elem?.style.setProperty('--el-input-hover-border-color', 'var(--el-border-color-hover)')
        elem?.style.setProperty('--el-input-focus-border-color', 'var(--el-color-primary)')
      }
    }
    catch (e) {}
  }
  function validate() {
    const showError = (_uuid_: string, prop: string) => {
      let elem = document.getElementById(`id_${_uuid_}_${prop}`)?.parentNode as HTMLElement
      if (prop === 'unitId' || prop === 'indicatorName')
        elem = document.getElementById(`id_${_uuid_}_${prop}`)?.querySelector('.el-input__wrapper') as HTMLElement
      elem?.style.setProperty('--el-input-border-color', 'var(--el-color-danger)')
      elem?.style.setProperty('--el-input-hover-border-color', 'var(--el-color-danger)')
      elem?.style.setProperty('--el-input-focus-border-color', 'var(--el-color-danger)')
    }
    // 校验之前先清除错误提示
    clearError()
    let isOk = true
    try {
      for (const item of unref(tpls)) {
        const _uuid_ = item._uuid_
        if (isInvalid(item.measuringPointNumber)) {
          isOk = false
          showError(_uuid_, 'measuringPointNumber')
        }
        // if (isInvalid(item.indicatorNumber)) {
        //   isOk = false
        //   showError(_uuid_, 'indicatorNumber')
        // }
        if (isInvalid(item.indicatorName)) {
          isOk = false
          showError(_uuid_, 'indicatorName')
        }
        if (isInvalid(item.unitId)) {
          isOk = false
          showError(_uuid_, 'unitId')
        }
        // if (isInvalid(item.indicatorCode)) {
        //   isOk = false
        //   showError(_uuid_, 'indicatorCode')
        // }
        // if (isInvalid(item.indicatorMultiple)) {
        //   isOk = false
        //   showError(_uuid_, 'indicatorMultiple')
        // }
      }
    }
    catch (e) {}
    return isOk
  }

  return {
    tpls,
    loading,
    /**
     * 获取模板数据
     * @param energyCode 能源品种代码
     * @example 023300
     * @param pointCode 用能单元编码
     * @example EU001
     * @param code 计量器具编码
     * @example CCL_030201
     */
    getTplsByEnergyCode,
    /** 移除指标 */
    removeIndicator,
    /** 创建空模板 */
    createEmptyTpl,
    /** 保存 */
    saveTps,
    /** 移除某一个校验错误 */
    removeOneError,
    /** 添加某一个校验错误 */
    addOneError,
    /** 必填校验 */
    isInvalid,
  }
}
